import merge from 'deepmerge'
import { ref } from 'vue'
import { defineModule } from './0-ViteSSGModule'

declare global {
  let config: {
    /**
     * the base configuration of app
     */
    readonly base: AppConfig
    /**
     * extra configurations which will be merged with base
     */
    readonly arr: Partial<AppConfig>[]
  }
}
export const appConfig = ref(config.base)

/**
 * modify app config in runtime
 * @param v
 */
export function setAppConfig(v: Partial<AppConfig>) {
  appConfig.value = merge(appConfig.value, v)
}

export default defineModule(() => {
  let cfg = appConfig.value
  if (cfg) {
    // merge the env related configs(development config, production config, etc.)
    const arr = config.arr
    for (const item of arr) cfg = merge(cfg, item)
    appConfig.value = cfg
    console.debug('merged app config: ', cfg)
  } else {
    throw new Error('app config base not set')
  }
  return appConfig
})
